package com.gome.boot.config.gfs;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;

/**
 * GFS客户端工具.
 *
 * @author baoxiufeng
 */
public class GfsClient {

    /**
     * GFS接口地址
     */
    private String apiUrl;

    /**
     * GFS接口token
     */
    private String apiToken;

    /**
     * 构造方法.
     *
     * @param apiUrl GFS接口地址
     * @param apiToken GFS接口token
     */
    public GfsClient(String apiUrl, String apiToken) {
        this.apiUrl = apiUrl;
        this.apiToken = apiToken;
    }

    /** HttpClient客户端 */
    private static CloseableHttpClient client = HttpClients.createDefault();

    /**
     * 上传文件到GFS服务器.
     *
     * @param file 要上传的文件
     * @return GFS服务返回的文件路径和文件扩展名
     * @throws Exception 异常信息
     */
    public String[] upload(File file) throws Exception {
        return handleUpload(file.getName(), new FileInputStream(file));
    }

    /**
     * 上传文件到GFS服务器
     *
     * @param imageUrl 要上传的文件远程路径
     * @return GFS服务返回的文件路径和文件扩展名
     * @throws Exception 异常信息
     */
    public String[] upload(String imageUrl) throws Exception {
        String filename = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
        return handleUpload(filename, new URL(imageUrl).openStream());
    }

    /**
     * 上传文件到GFS服务器
     *
     * @param filename 要上传的文件名称
     * @param is 要上传的文件内容输入流
     * @return GFS服务返回的文件路径和文件扩展名
     * @throws Exception 异常信息
     */
    public String[] upload(String filename, InputStream is) throws Exception {
        return handleUpload(filename, is);
    }

    /**
     * 上传图片到GFS服务器.
     *
     * @param filename 文件名
     * @param is 文件输入流
     * @return 文件GFS路径
     * @throws Exception 异常信息
     */
    private String[] handleUpload(String filename, InputStream is) throws Exception {
        String suffix = filename.substring(filename.lastIndexOf("."));
        String url = String.format(apiUrl, filename, suffix);
        ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
        byte[] b = new byte[1024];
        int n = 0;
        while ((n = is.read(b)) != -1) {
            bos.write(b, 0, n);
        }
        HttpPost post = new HttpPost(url);
        post.addHeader("token", apiToken);
        post.setEntity(new ByteArrayEntity(bos.toByteArray()));
        CloseableHttpResponse response = client.execute(post);
        String result = EntityUtils.toString(response.getEntity());
        is.close();
        bos.close();
        return new String[] { result, suffix.toLowerCase() };
    }
}
